package yu.ac.bg.etf.kdp.klase;

import java.io.*;
import java.net.*;

import yu.ac.bg.etf.kdp.klase.*;

public class FileTransfer {

	public static void sendFile (ObjectOutputStream out, String fileName) {
			ServerSocket serverSocket;
			try {
				serverSocket = new ServerSocket(4001);
				InetAddress localMachine = InetAddress.getLocalHost();
				out.writeObject(new MsgTxt(localMachine.getHostName()));
				out.flush();
				out.writeObject(new MsgTxt(""+serverSocket.getLocalPort()));
				out.flush();
				System.out.println("CHECK1");
				Socket socket = serverSocket.accept();
				System.out.println("CHECK2");
				BufferedInputStream bis;
				System.out.println("CHECK3");
				BufferedOutputStream bos;
				System.out.println("CHECK4");
				int in;
				try {
					bos=new BufferedOutputStream(socket.getOutputStream());
					bos.flush();
					bis = new BufferedInputStream(new FileInputStream(fileName));
					byte[] sendData=new byte[8192];
					while((in=bis.read(sendData))!=-1){
						bos.write(sendData, 0,in);
						bos.flush();
					}
					bis.close();
					bos.close();
				} catch (FileNotFoundException e) {
					// TODO: handle exception
					System.out.println("File "+fileName+" not found..");
				}
				serverSocket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				System.out.println("Connection broken..");
			}
	}
	
	public static void recieveFile (ObjectInputStream ino, String fileName) {
		try {
			Msg m = (MsgTxt)ino.readObject();
			String host = (String)m.getBody();
			int port = Integer.parseInt((String)(((Msg)ino.readObject()).getBody()));
			Socket socket = new Socket(host, port);
			
			System.out.println("Ready to receive");
			BufferedInputStream bis;
			BufferedOutputStream bos;
			int in;

			byte[] recievedData = new byte[8192];
			bos = new BufferedOutputStream(new FileOutputStream(fileName));
			bis = new BufferedInputStream(socket.getInputStream());
			while ((in = bis.read(recievedData)) != -1)
				bos.write(recievedData,0,in);
			System.out.println("File Recieved Successfully");
			bos.close();
			bis.close();
		} catch(Exception e) {
			System.out.println("Connection broken..");
		}
	}
	
}
